
import React, { useEffect, useRef, useState } from "react";
import { getLayout } from '@/components/Layout'
import {
    Button,
    Table, Pagination,
    Popconfirm, Space,
    PaginationProps, Modal, Form, Input, message, InputRef
} from "antd";
import {
    EditOutlined, SearchOutlined,
    DeleteOutlined, QuestionCircleOutlined
} from '@ant-design/icons';
import { ColumnsType } from "antd/es/table";
import { creatUser, deleteUser, editUser, getUserList } from "@/api/userCenter";
import style from './index.module.scss'
import { FilterConfirmProps } from "antd/es/table/interface";

type FieldType = {
    id: string;
    username?: string;
    password?: string;
};
function userCenter() {
    const isFistRender = useRef(true)
    const [userList, setUserList] = useState([])
    const [userForm, setUserForm] = useState({} as FieldType)
    const [isModalOpen, setIsModalOpen] = useState(false)
    const [submitType, setSubmitType] = useState('create')
    const [currentId, setCurrentId] = useState('')
    const [total, setTotal] = useState(0)
    const [pageNo, setPageNo] = useState(1)
    const [pageSize, setPageSize] = useState(10)
    const showTotal: PaginationProps['showTotal'] = (total) => `共 ${total} 条`;

    const [form] = Form.useForm();

    //搜索相关
    const searchInput = useRef<InputRef>(null);
    const [searchContent, setSearchContent] = useState('')

    const columns: ColumnsType<FieldType> = [
        {
            title: 'ID',
            dataIndex: 'id',
            width: '15%',
            key: 'id',
        },
        {
            title: '用户名',
            dataIndex: 'username',
            key: 'username',
            width: '40%',
            filterDropdown: ({ setSelectedKeys, selectedKeys, confirm, clearFilters }) => (
                <div style={{ padding: 8 }}>
                    <Input
                        ref={searchInput}
                        placeholder={'搜索用户名'}
                        value={selectedKeys[0]}
                        onChange={e => setSelectedKeys(e.target.value ? [e.target.value] : [])}
                        onPressEnter={() => handleSearch(selectedKeys, confirm)}
                        style={{ width: 188, marginBottom: 8, display: 'block' }}
                    />
                    <Space>
                        <Button
                            type="primary"
                            onClick={() => handleSearch(selectedKeys, confirm)}
                            size="small"
                            icon={<SearchOutlined />}
                            style={{ padding: '0 12px', width: 90 }}
                        >
                            搜索
                        </Button>
                        <Button
                            onClick={() => clearFilters && handleReset(clearFilters)}
                            size="small"
                            style={{ width: 90 }}
                        >
                            重置
                        </Button>
                    </Space>
                </div>
            ),
            onFilterDropdownOpenChange: (visible) => {
                if (visible) {
                    setTimeout(() => searchInput.current?.select(), 100);
                }
            },
            filterIcon: (filtered: boolean) => {
                return (
                    <SearchOutlined style={{ color: filtered ? '#1677ff' : undefined }} />
                )
            },
        },
        {
            title: '密码',
            dataIndex: 'password',
            width: '15%',
            key: 'password',
        },
        // {
        //     title: '创建时间',
        //     dataIndex: 'createTime',
        //     width: '15%',
        //     key: 'createTime',
        // },
        {
            title: '操作',
            width: '30%',
            key: 'action',
            render: (_, record) => {
                return (
                    <Space size="middle">
                        <Button
                            type="primary"
                            className='edit-btn'
                            onClick={() => clickEdit(record)}
                            icon={<EditOutlined />}
                        >编辑
                        </Button>
                        <Popconfirm
                            title={record.username}
                            description="是否确认删除此用户?"
                            icon={<QuestionCircleOutlined style={{ color: 'red' }} />}
                            onConfirm={() => handleDeleteUser(record.id)}
                        >
                            <Button
                                type="text"
                                className='delete-btn'
                                icon={<DeleteOutlined />}
                            >删除</Button>
                        </Popconfirm>
                    </Space>
                )
            },
        },
    ];

    useEffect(() => {
        if (isFistRender.current) {
            getUserListByQuery()
            isFistRender.current = false
        } else {
            getUserListByQuery()
            listScrollTop()
        }
    }, [pageNo, pageSize, searchContent])

    // 重置搜索内容
    const handleReset = (clearFilters: () => void) => {
        clearFilters();
        setSearchContent('');
    };

    // 搜索用户名
    const handleSearch = (selectedKeys: any[],
        confirm: (param?: FilterConfirmProps) => void,) => {
        confirm();
        setSearchContent(selectedKeys[0])
    }

    // 列表滚动到顶部
    const listScrollTop = () => {
        const scrollDom = document.querySelector('.ant-layout-content');
        if (scrollDom) scrollDom.scrollTop = 0
    }

    // 提交表单
    const handleSubmit = () => {
        if (submitType === 'create') {
            handleCreatUser()
        } else {
            handleEditUser();
        }
    }
    //  获取用户列表
    const getUserListByQuery = () => {
        const params = {
            pageNo,
            pageSize,
            searchContent
        }
        getUserList(params).then(res => {
            const {
                list = [],
                total = 0
            } = res?.data?.body ?? {}
            setUserList(list)
            setTotal(total)
        })
    }
    // 点击新建按钮
    const clickCreate = () => {
        form.setFieldsValue({
            username: '',
            password: ''
        });
        handleShowModal(true);
        setSubmitType("create");
    }
    //  新建用户
    const handleCreatUser = () => {
        creatUser(userForm).then(res => {
            if (res.data.code !== '200') {
                message.error(res.data.message)
            } else {
                handleShowModal(false);
                getUserListByQuery();
            }
        })
    }
    // 点击编辑按钮
    const clickEdit = (record: FieldType) => {
        form.setFieldsValue(record);
        setCurrentId(record.id);
        handleShowModal(true);
        setSubmitType("edit");
    }
    //  编辑用户
    const handleEditUser = () => {
        editUser({ id: currentId, data: userForm }).then(res => {
            if (res.data.code !== '200') {
                message.error(res.data.message)
            } else {
                handleShowModal(false);
                getUserListByQuery();
            }
        })
    }
    //  删除用户
    const handleDeleteUser = (id: string) => {
        deleteUser(id).then(res => {
            getUserListByQuery();
        })
    }
    // 控制用户弹窗
    const handleShowModal = (state: boolean) => {
        setIsModalOpen(state);
    };
    //  用户名输入框
    const handleUserNameChange = (event: any) => {
        setUserForm({
            ...userForm,
            username: event.target.value
        })
    }
    //  密码输入框
    const handlePasswordChange = (event: any) => {
        setUserForm({
            ...userForm,
            password: event.target.value
        })
    }
    return (
        <div className={style.user_center}>
            <Button type="primary" className='add-btn' onClick={clickCreate}>新建</Button>
            <Table
                columns={columns}
                pagination={false}
                dataSource={userList}
                rowKey="id"
            />
            <Pagination
                className="pagination"
                showSizeChanger
                showQuickJumper
                showTotal={showTotal}
                current={pageNo}
                onChange={(page: number) => setPageNo(page)}
                onShowSizeChange={(page: number, size: number) => {
                    setPageNo(page)
                    setPageSize(size)
                }}
                total={total}
            />
            <Modal
                title={submitType === 'create' ? '新建用户' : '编辑用户'}
                open={isModalOpen}
                onOk={() => handleShowModal(false)}
                onCancel={() => handleShowModal(false)}
                footer={null}
            >
                <Form
                    form={form}
                    name="basic"
                    labelCol={{ span: 3 }}
                    wrapperCol={{ span: 21 }}
                    style={{ maxWidth: 600, marginTop: 40 }}
                    initialValues={{ remember: true }}
                    autoComplete="off"
                >
                    <Form.Item<FieldType>
                        label="用户名"
                        name="username"
                        rules={[{ required: true, message: '请输入用户名' }]}
                    >
                        <Input
                            value={userForm.username}
                            onChange={handleUserNameChange}
                        />
                    </Form.Item>

                    <Form.Item<FieldType>
                        label="密码"
                        name="password"
                        rules={[{ required: true, message: '请输入密码' }]}
                    >
                        <Input.Password
                            value={userForm.password}
                            onChange={handlePasswordChange} />
                    </Form.Item>
                    <Form.Item wrapperCol={{ offset: 11, span: 13 }}>
                        <Button onClick={handleSubmit} type="primary" htmlType="submit">
                            提交
                        </Button>
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    );
}

export default getLayout(userCenter);
